package com.yuyou.tas.job.service;

import com.yuyou.tas.job.service.Async.AsyncService;
import com.yuyou.tas.service.api.admin.entity.CommJob;
import com.yuyou.tas.service.api.admin.service.CommJobAPI;
import com.yuyou.tas.service.api.lesson.entity.LessonResource;
import com.yuyou.tas.service.api.lesson.service.LessonResourceAPI;
import com.yuyou.tas.util.enums.admin.CommJobEnums;
import com.yuyou.tas.util.tool.LogUtil;
import com.yuyou.tas.util.tool.Sequence;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ResBatchScheduled {
 
	@Autowired
	private CommJobAPI commJobAPI;

	@Autowired
	private LessonResourceAPI lessonResourceAPI;

	@Autowired
	private AsyncService asyncService;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	// 每隔60秒执行任务 
	@Scheduled(cron="0 0/1 * * * ?")
    public void executeFileDownLoadTask() throws Exception { 
        
		//本批次的分派标识
        Long allotTempId=Sequence.getSequence().nextId();
		commJobAPI.updateLoadedJob(allotTempId);
        
		//通过分派标识查出本批次任务列表
		List<CommJob> jobList=commJobAPI.findLoadedJob(allotTempId);
		if(CollectionUtils.isEmpty(jobList)){
			return;
		}

		for(CommJob job:jobList){
			if(CommJobEnums.type.resource.getValue() == job.getType()){
				LogUtil.info(logger , "获取删除任务："+job.getId());
				asyncService.AsyncDeleteJob(job.getfId(),job.getId());//放入线程池
			}else if(CommJobEnums.type.feedbackSituation.getValue() == job.getType()){
				LogUtil.info(logger , "获取反馈图片音频处理任务："+job.getfId());
                asyncService.AsynUploadJob(job);
            }else if(CommJobEnums.type.feedbackNote.getValue() == job.getType()){
				LogUtil.info(logger , "获取反馈优秀学生笔记处理任务："+job.getfId());
                asyncService.AsynUploadJob(job);
            }
			/*LessonResource lr=lessonResourceAPI.selectById(job.getfId());
			officeAPI.deleteFileMetas(lr.getResourceId());*/
		}
		
		
        
    }

    //每天0点执行
    @Scheduled(cron = "0 0 0 * * ?")
    public void executeTempResourceTask(){
		List<LessonResource> list = lessonResourceAPI.selectTemps();//获取插入超过一天的临时数据
		if(CollectionUtils.isEmpty(list)){
			return;
		}
		List<String> resourceIds = new ArrayList<>();
		for (LessonResource lr:list
			 ) {
			commJobAPI.addResourceJob(lr.getResourceId() , CommJobEnums.type.resource.getValue() , CommJobEnums.tag.resource.getValue());//加入删除任务
			resourceIds.add(lr.getResourceId());
		}
		String[] ids = new String[resourceIds.size()];//删除lessonResource记录
		resourceIds.toArray(ids);
		lessonResourceAPI.delByResourceIds(ids);
	}
}
